package com.example.config.event;

import com.example.event.event.CustomEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author LiYuhang
 * @version 0.1
 * @application 开启异步调用支持
 * @Date 2020/9/20 22:17
 */
@Configuration
@Slf4j
@EnableAsync
public class EventConfig {
    @EventListener
    public void handle(Object event){
        //监听所有事件
        log.info("监听所有事件：{}",event);
    }
    @EventListener
    public void handleCustomEvent(CustomEvent customEvent){
        //监听CustomEvent事件
        log.info("监听到CustomEvent事见 >> 消息为：{} >> 时间为：{}",customEvent.getMessage(),stampToDate(customEvent.getTimestamp()));
    }

    /**
     * 异步调用
     * @param customEvent
     */
    @Async
    @EventListener(condition = "#customEvent.message.code=='ok'")
    public void handleCustomEventByCondition(CustomEvent customEvent){
         //监听 customEvent.message.code=='ok'
        try {
            for (int i = 0; i < 10; i++) {
                log.info("监听到CustomEvent事件 message.code = OK >> 消息为：{} >> 时间为：{} >> nowTime：{}",customEvent.getMessage(),stampToDate(customEvent.getTimestamp()),stampToDate(System.currentTimeMillis()));
                Thread.sleep(100L);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("调用结束：截止时间：{}",stampToDate(System.currentTimeMillis()));
        //log.info("监听到CustomEvent事件 message.code = OK >> 消息为：{} >> 时间为：{}",customEvent.getMessage(),customEvent.getTimestamp());
    }

    public static String stampToDate(long  s){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss-SSS");
        Timestamp t = new Timestamp(s);
        Date date = new Date(t.getTime());
        return simpleDateFormat.format(date);
    }

}
